package org.summerframework.web.exception.resolver;

import org.summerframework.core.base.result.DefaultResultCode;
import org.summerframework.core.base.result.ResultCode;
import org.summerframework.core.base.result.ResultDTO;
import org.summerframework.web.view.DefaultMappingJackson2JsonView;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author 石超
 * @version v1.0.0
 */

public class BindExceptionResolveHandler implements ExceptionResolveHandler {
    @Resource
    private DefaultMappingJackson2JsonView defaultMappingJackson2JsonView;

    @Override
    public ResultCode resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        BindingResult bindResult = ((BindException) ex).getBindingResult();
        List<FieldError> fieldErrors = bindResult.getFieldErrors();

        if (CollectionUtils.isNotEmpty(fieldErrors)) {
            return DefaultResultCode.getInstance(DefaultResultCode.ILLEGAL_ARGUMENT_CHECK.getCode(), fieldErrors.get(0).getDefaultMessage());
        }

        return DefaultResultCode.ERROR_REQUEST_BAD_REQUEST;
    }

    @Override
    public boolean supper(Exception ex) {
        return ex instanceof BindException;
    }

    @Override
    public ModelAndView determineModelAndView(HttpServletRequest request, ResultDTO resultDTO, boolean isHtml, Exception e) {
        if (resultDTO.getCode().getCode() == DefaultResultCode.ILLEGAL_ARGUMENT_CHECK.getCode()) {
            ModelAndView modelAndView = new ModelAndView(defaultMappingJackson2JsonView);
            modelAndView.addObject(resultDTO);
            return modelAndView;
        } else {
            return null;
        }
    }
}
